3. 数据处理基础
3.1运算符与运算函数
在pandas中如果要做数组运算,一般是单值、Series(一维数组)、DataFrame(二维数组)之间的运算。
运算符类型 | 运算符 | 函数 | 注释 |
---|---|---|---|
算术运算符 | + | add | 加 |
- | sub | 减 | |
* | mul | 乘 | |
/ | div | 除 | |
求模运算符 | % | mod | 求余数 |
求幂运算符 | ** | pow | 求幂 |
比较运算符 | == | 等于 | |
!= | 不等于 | ||
> | 大于 | ||
>= | 大于或等于 | ||
连接运算符 | + | 连接 | |
逻辑运算符 | & | and | 与 |
| | or | 非 | |
~(波浪号) | nto | 或 |
import pandas as pd
s=pd.Series([ 2,3,5 ])
print (s+8)
print (s-8)
print (s*8)
print (s/8)
返回:
0 | 10 |
1 | 11 |
2 | 13 |
dtype: int64
0 | -6 |
1 | -5 |
2 | -3 |
dtype: int64
0 | 16 |
1 | 24 |
2 | 40 |
dtype: int64
0 | 0.250 |
1 | 0.375 |
2 | 0.625 |
dtype: float64
import pandas as pd
s=pd.Series([ 2,3,5 ])
print (s.add( 10 ))
print (s.sub( 10 ))
print (s.mul( 10 ))
print (s.div( 10 ))
返回:
0 | 12 |
1 | 13 |
2 | 15 |
dtype: int64
0 | -8 |
1 | -7 |
2 | -5 |
dtype: int64
0 | 20 |
1 | 30 |
2 | 50 |
dtype: int64
0 | 0.2 |
1 | 0.3 |
2 | 0.5 |
dtype: float64
import pandas as pd
s=pd.Series([ 2,3,5 ])
print (s%2) #求余数
print (s**3) #求n次方
返回:
0 | 0 |
1 | 1 |
2 | 1 |
dtype: int64
0 | 8 |
1 | 27 |
2 | 125 |
dtype: int64
import pandas as pd
s=pd.Series([ 2,3,5 ])
print (s==2)
print (s!=3)
print (s>3)
print ((s>=3)*1)
返回:
0 | True |
1 | False |
2 | False |
dtype: bool
0 | True |
1 | False |
2 | True |
dtype: bool
0 | False |
1 | False |
2 | True |
dtype: bool
0 | 0 |
1 | 1 |
2 | 1 |
dtype: int32
import pandas as pd
print ((2>3) & (2>1))
print ((2>3) | (2>1)) #需要加括号,不然优级先级是3 | 2
print (~ 2>3 )
返回:
False |
True |
False |